<template>
    <div id="login">
        <div class="login-form" :style="{top:top}">
            <h3 class="login-title">
                <TeamOutlined style="position: relative;font-size: 30px;"/>
                网 站 后 台 管 理 系 统
            </h3>
            <div class="form-item">
                <a-input v-model:value="username" autofocus placeholder="用户名" size="large">
                    <template #prefix>
                        <UserOutlined/>

                    </template>
                </a-input>
            </div>
            <div class="form-item">
                <a-input-password v-model:value="password" placeholder="密码" size="large">
                    <template #prefix>
                        <LockOutlined/>
                    </template>
                </a-input-password>
            </div>
            <div class="form-item" style="height: 45px;">
                <div id="verify_type"></div>
            </div>
            <div class="form-item" style="margin: 2px 0 0;">

                <a-button type="link" style="color: darkgrey;float: right;font-size: 12px;"
                          @click="visible = true">
                    <KeyOutlined style="position: relative;left: 5px;"/>
                    忘记密码?
                </a-button>
                <div class="clearfix"></div>

            </div>
            <div class="form-item" style="margin: 5px 0 0 0;">
                <a-button :type="loginBtnBg"
                          @click="login"
                          :loading="isLogin"
                          block="true"
                          size="large"
                          :disabled="loginBtnDisable"
                >
                    <template #icon>
                        <LoginOutlined/>
                    </template>
                    立即登录
                </a-button>
            </div>
        </div>
        <p id="foot" style="position: fixed;text-align: center;bottom: 0;left: 0;right: 0;color: #707070;">版权所有 星时代爪哇
            Copyright ©
            2021 - {{year}} <a href="https://beian.miit.gov.cn/" target="_blank"
                               style="text-decoration: none;">蜀ICP备2020030393号-1</a></p>
    </div>
    <a-modal
            v-model:visible="visible"
            title="忘记密码"
            centered
            :footer="null"
            @ok="visible = false"
    >
        <div v-if="!okVisible" style="margin: 15px 15px;">
            <div>
                <a-input v-model:value="email" placeholder="请输入QQ邮箱" size="large" autofocus>
                    <template #addonAfter>
                        <div style="cursor: pointer;" @click="getYzm()">
                            <MailOutlined style="color: #d9d9d9;"/>
                            获取验证码
                        </div>
                    </template>
                </a-input>

            </div>
            <div style="padding-top: 20px;">
                <a-row>
                    <a-col :span="16">
                        <a-input v-model:value="yzm" placeholder="请输入验证码" size="large">

                        </a-input>
                    </a-col>
                    <a-col :span="8" style="text-align: right;">
                        <a-button type="primary" size="large" @click="unlock">
                            <UnlockOutlined/>
                            立即解锁
                        </a-button>
                    </a-col>
                </a-row>
                <p style="padding-top: 10px;margin: 0;color: #bcbcbc;">
                <p style="color: #ffa600;margin: 5px 0;">
                    <BulbOutlined/>
                    提示：
                </p>
                <p style="font-size: 12px;">
                    1、输入邮箱号，点击按钮获得验证码。
                    <br>
                    2、输入验证码，点击立即解锁。
                    <br>
                    3、请尽快完成验证！
                </p>
                </p>
            </div>
        </div>

        <div v-else style="margin: 15px 15px;">
            <a-result
                    status="success"
                    title="恭喜你,解锁成功！"
                    sub-title="Congratulations, unlocking success!"
            >
                <template #extra>
                    <a-button key="console" type="primary" @click="goLogin()">立即登录</a-button>
                    <a-button key="buy" @click="okVisible=false;">返回</a-button>
                </template>
            </a-result>
        </div>

    </a-modal>
</template>

<script>
    import {
        TeamOutlined,
        LoginOutlined,
        LockOutlined,
        GithubOutlined,
        QqOutlined,
        BankOutlined,
        MailOutlined,
        UnlockOutlined,
        KeyOutlined,
        BulbOutlined,
        UserOutlined
    } from "@ant-design/icons-vue"
    import {findPassword, login, sendYzm as sendYzmApi} from "../api/admin"
    import {message, notification, Modal} from "ant-design-vue"


    /**
     * Notes: js滑动块验证码封装方法
     * User: ZHL
     * Date: 2020/5/14
     */
    var verifyFun = {
        bar: function (item) {
            let html = '<div class="verify_box noselect"><div class="verify_forward_box"></div><div class="verify_drag_box" > > </div><div class="verify_tip">向右滑动></div></div>';
            item.dom.innerHTML = html;
            var verifyBox = item.dom.children[0];					// 滑道DOM
            var verifyLayer = item.dom.children[0].children[0];		// 遮罩层DOM
            var verifyDom = item.dom.children[0].children[1];		// 滑动块DOM
            var verifyTip = item.dom.children[0].children[2];		// 提示信息DOM
            verifyBox.style.width = parseInt(item.width) + 'px'; 		// 盒子宽
            verifyBox.style.height = parseInt(item.height) + 'px';	// 盒子高
            verifyDom.style.lineHeight = parseInt(item.height) + 'px';// 行高
            verifyDom.style.fontSize = parseInt(item.size) + 'px';	// 滑动块字体大小
            verifyDom.style.width = parseInt(item.height) + 'px';		// 滑块宽等于高
            verifyTip.style.fontSize = parseInt(item.hsize) + 'px';	// 提示文字大小
            verifyTip.style.lineHeight = parseInt(item.height) + 'px';// 提示文字行高
            var slideNum = parseInt(item.width) - parseInt(item.height); 	// 最大滑动距离
            var x = 0;
            var y = 0;
            var l = 0;
            var t = 0;
            var flag = false; // 开关
            /** PC-鼠标按下事件 **/
            verifyDom.onmousedown = function (e) {
                onstart(e);
            }
            /** PC-鼠标移动事件 **/
            verifyDom.onmousemove = function (e) {
                oncarry(e);
            }
            /** PC-鼠标抬起事件 **/
            verifyDom.onmouseup = function (e) {
                onend(e);
            }

            /** M-手指放到屏幕上时 **/
            verifyDom.ontouchstart = function (e) {
                onstart(e);
            }

            /** M-手指在屏幕上滑动时 **/
            verifyDom.ontouchmove = function (e) {
                oncarry(e);
            }

            /** M-手指离开屏幕时 **/
            verifyDom.ontouchend = function (e) {
                onend(e);
            }
            /** 鼠标移除事件 **/
            verifyDom.onmouseout = function (e) {
                flag = false;
                var ll = verifyDom.offsetLeft;
                if (ll < (slideNum - item.diff)) {
                    verifyDom.style.left = l + 'px';
                    verifyDom.style.top = t + 'px';
                    verifyLayer.style.zIndex = 1;
                }
            }

            /** 一、鼠标按下事件/移动端手指放到屏幕上时触发方法 **/
            function onstart(e) {
                //获取x坐标和y坐标
                x = typeof (e.clientX) !== "undefined" ? e.clientX : e.changedTouches[0].clientX;
                y = typeof (e.clientY) !== "undefined" ? e.clientY : e.changedTouches[0].clientY;
                //获取左部和顶部的偏移量
                l = verifyDom.offsetLeft;
                t = verifyDom.offsetTop;
                flag = true;
            }

            /** 二、鼠标移动事件/移动端手指放到屏幕上时触发方法 **/
            function oncarry(e) {
                if (flag == false) {
                    return;
                }
                //获取移动时x坐标和y坐标
                var nx = typeof (e.clientX) !== "undefined" ? e.clientX : e.changedTouches[0].clientX;
                var ny = typeof (e.clientY) !== "undefined" ? e.clientY : e.changedTouches[0].clientY;
                ny = y; // 水平滑动不让上下滑动，所以y始终一致
                nx = nx < x ? x : nx; // 控制最小
                nx = nx - slideNum > x ? slideNum + x : nx; // 控制最大
                //计算移动后的左偏移量和顶部的偏移量
                var nl = nx - (x - l);
                var nt = ny - (y - t);
                verifyDom.style.left = nl + 'px';
                verifyDom.style.top = nt + 'px';
                if (nl > (slideNum - item.diff)) {
                    verifyDom.style.left = slideNum + 'px';
                    verifyDom.style.top = t + 'px';
                    verifyLayer.style.zIndex = 5;
                    verifyDom.innerHTML = '&radic;';
                    verifyDom.style.color = '#0a6af9';
                    verifyDom.style.background = '#00d131';
                    item.dom.children[0].style.border = '0px solid #0a6af9';
                    verifyTip.innerText = '验证通过';
                    verifyTip.style.color = '#ffffff';
                    verifyBox.style.background = '#00d162';
                    item.success();
                }
            }

            /** 三、鼠标抬起事件/手指离开屏幕时触发方法 **/
            function onend(e) {
                flag = false;
                var ll = verifyDom.offsetLeft;
                if (ll < (slideNum - item.diff)) {
                    verifyDom.style.left = l + 'px';
                    verifyDom.style.top = t + 'px';
                    item.error();
                } else {
                    verifyDom.style.left = slideNum + 'px';
                    verifyDom.style.top = t + 'px';
                    verifyLayer.style.zIndex = 5;
                    verifyDom.innerHTML = '&radic;';
                    verifyDom.style.color = '#0a6af9';
                    item.dom.children[0].style.border = '1px solid #0a6af9';
                    verifyTip.innerText = '验证通过';
                    verifyBox.style.background = '#fff';
                    item.success();
                }
            }

        },
    };


    export default {
        name: "Login",
        created() {
            setTimeout(() => {
                this.top = 0;
            }, 1)
            this.year = new Date().getFullYear();
        },
        mounted() {
            var that = this;
            var type = document.getElementById('verify_type');
            verifyFun.bar({
                dom: type,		// dom对象
                width: '350',	// 盒子宽
                height: '40',	// 盒子高
                hsize: '12',		// 提示字体大小
                size: '20',		// 滑动块箭头字体大小
                diff: 2,			// 误差值
                success: function () {
                    // alert('验证成功');
                    //其他业务逻辑
                    that.loginBtnBg = "primary";
                    that.loginBtnDisable = false;
                    message.success("验证成功")
                },
                error: function () {
                    // alert('验证失败！');
                    //其他业务逻辑
                }
            });

        },
        data() {
            return {
                username: '',
                password: '',
                isLogin: false,
                top: "300px",
                year: "",
                visible: false,
                email: "",
                yzm: "",
                okVisible: false,
                loginBtnBg: "default",
                loginBtnDisable: true,
        }
            ;
        },
        components: {
            LoginOutlined,
            GithubOutlined,
            QqOutlined,
            LockOutlined,
            BankOutlined,
            MailOutlined,
            UnlockOutlined,
            TeamOutlined,
            KeyOutlined,
            BulbOutlined,
            UserOutlined,
        },
        methods: {
            login() {
                //前端验证
                if (this.username == "" || this.password == "") {
                    this.$message.warning("用户名或密码不能为空");
                    return false;
                }
                this.isLogin = true;
                login(this.username, this.password).then(resp => {
                    if (resp.code == 200) {
                        this.$message.success("登录成功");
                        sessionStorage.setItem("userInfo", JSON.stringify(resp.data));
                        this.$router.push("/admin");
                    } else if (resp.code == 1000) {
                        this.$message.error(resp.message);
                    }
                }).catch(err => {
                    console.error(err);
                    this.$message.error("请求失败,请检查接口地址");
                }).finally(() => {
                    this.isLogin = false;
                })
            },
            goLogin() {
                this.okVisible = false;
                this.visible = false;
            },
            getYzm() {
                if (this.email == "") {
                    message.warn("请输入你的邮箱地址");
                    return false;
                }
                message.info("正在获取验证码~~~")
                sendYzmApi(this.email).then(resp => {
                    if (resp.code == 200) {
                        notification.info({
                            message: '温馨提示',
                            description: "系统已经向你的邮箱发送了一封电子邮件，请注意查收！并在5分钟内完成验证操作！",
                            duration: "10"
                        });
                    } else {
                        notification.error({
                            message: '错误',
                            description: resp.message,
                        });
                    }
                })
            },
            unlock() {
                if (this.email == "" || this.yzm == "") {
                    message.warn("稍安勿躁，请先阅读提示，按照正确步骤找回密码！")
                    return false;
                }
                findPassword(this.email, this.yzm).then(resp => {
                    console.log(resp)
                    if (resp.code == 200) {
                        message.success("解锁成功")
                        notification.success({
                            message: '成功',
                            description: "恭喜，验证通过，解锁成功！请尽快登录并修改密码！",
                        })

                        notification.success({
                            message: '成功',
                            description: "你的临时登录密码为：" + resp.data + "，请利用临时密码登录并尽快修改密码",
                            duration: 30
                        })
                        this.okVisible = true;
                        notification.warn({
                            message: '警告',
                            description: "系统检测到你刚刚利用找回密码功能登录，目前账号处于不安全状态，请你尽快修改密码！",
                            duration: "15"
                        })
                    } else {
                        const errMsg = "对不起，" + resp.message + "，解锁失败！"
                        message.error("解锁失败")
                        notification.error({
                            message: '失败',
                            description: errMsg,
                        });
                        Modal.error({
                            title: "解锁失败",
                            content: errMsg,
                            centered: true,
                            okText: "确定"
                        })
                    }
                })
            }
        }
    }
</script>

<style scoped lang="less">
    #login {
        height: 100vh;
        background: url("../assets/login_bg.png");
        background-size: 100% 100%;
    }

    .login-form {
        position: absolute;
        left: -35%;
        top: 100px;
        bottom: 0;
        right: 0;
        margin: auto;
        height: 350px;
        background: #fff;
        width: 400px;
        padding: 25px;
        transition: top 0.5s;
        box-shadow: 5px 5px 15px darkgrey;

        h3.login-title {
            text-align: left;
            display: block;
            font-size: 18px;
            font-weight: bold;
            color: #707070;
            margin: 5px 0 25px;
            padding: 0;
        }

        .form-item {
            margin-top: 16px;
        }

    }

    @media screen and (max-width: 768px) {
        .login-form {
            height: 60%;
            width: 99%;
        }

        #foot {
            font-size: 12px;
        }
    }

</style>